import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPalette, QColor, QFont
from PyQt5.QtWidgets import (QApplication, QMainWindow, QDockWidget,
                             QWidget, QLabel)


class DemoDockWidget(QMainWindow):
    def __init__(self, parent=None):
        super(DemoDockWidget, self).__init__(parent)

        # 设置窗口标题
        self.setWindowTitle('实战PyQt5: QDockWidget Demo!')
        # 设置窗口大小
        self.resize(480, 360)

        self.initUi()

    def initUi(self):
        # 移除 CentralWidget
        self.takeCentralWidget()

        # 启动dock 嵌套
        self.setDockNestingEnabled(True)

        # 允许设置成Tab窗口样式
        self.setDockOptions(self.dockOptions() | QMainWindow.AllowTabbedDocks)

        docks = []
        for index in range(9):
            docks.append(self.crateDock(index))

        # ==== 九宫格布局 ====#

        # 将docks[0]停靠在主界面的左边
        self.addDockWidget(Qt.LeftDockWidgetArea, docks[0])
        # 将docks[0]和docks[1]水平排列
        self.splitDockWidget(docks[0], docks[1], Qt.Horizontal)
        # 将docks[1]和docks[2]水平排列
        self.splitDockWidget(docks[1], docks[2], Qt.Horizontal)

        # 将docks[0]和docks[3]垂直排列
        self.splitDockWidget(docks[0], docks[3], Qt.Vertical)
        # 将docks[1]和docks[4]垂直排列
        self.splitDockWidget(docks[1], docks[4], Qt.Vertical)
        # 将docks[2]和docks[5]垂直排列
        self.splitDockWidget(docks[2], docks[5], Qt.Vertical)

        # 将docks[3]和docks[6]垂直排列
        self.splitDockWidget(docks[3], docks[6], Qt.Vertical)
        # 将docks[4]和docks[7]垂直排列
        self.splitDockWidget(docks[4], docks[7], Qt.Vertical)
        # 将docks[5]和docks[8]垂直排列
        self.splitDockWidget(docks[5], docks[8], Qt.Vertical)

    def crateDock(self, index):
        colors = [Qt.red, Qt.lightGray, Qt.green,
                  Qt.blue, Qt.cyan, Qt.magenta,
                  Qt.yellow, Qt.gray, Qt.darkMagenta]
        dock = QDockWidget('dock ' + str(index + 1), self)
        wid = QLabel(self)
        # 字体设置大一点
        wid.setFont(QFont(self.font().family(), 24))
        wid.setText(str(index + 1))
        wid.setAlignment(Qt.AlignCenter)
        palette = wid.palette()
        palette.setColor(QPalette.Background, colors[index])
        wid.resize(160, 90)
        wid.setAutoFillBackground(True)
        wid.setPalette(palette)
        dock.setWidget(wid)
        wid.show()

        return dock


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = DemoDockWidget()
    window.show()
    sys.exit(app.exec())